const WebSocket = require("ws");

// 创建 WebSocket 服务器实例，监听所有网络接口的 8080 端口
const wss = new WebSocket.Server({ host: "0.0.0.0", port: 8088 });

// 存储在线用户
const users = new Map();
// 存储历史消息
const messageHistory = [];

// 生成随机用户ID
function generateUserId() {
  return `用户-${Math.floor(Math.random() * 10000)}`;
}

// 处理新客户端连接
wss.on("connection", (ws, req) => {
  console.log("收到新的连接请求");

  let userId = null;
  let userType = "customer";
  let heartbeatInterval;
  let lastPingTime = Date.now();

  try {
    // 生成用户ID
    userId = generateUserId();
    console.log(`新用户 ${userId} 已连接 (IP: ${req.socket.remoteAddress})`);

    // 设置用户信息
    ws.userId = userId;
    ws.userType = userType;
    ws.isAlive = true;

    // 添加到用户列表
    users.set(userId, ws);

    // 发送注册成功响应
    ws.send(
      JSON.stringify({
        type: "register",
        userId,
        userType,
      })
    );

    // 发送历史消息记录
    if (messageHistory.length > 0) {
      ws.send(
        JSON.stringify({
          type: "history",
          messages: messageHistory,
        })
      );
    }

    // 设置心跳检测
    heartbeatInterval = setInterval(() => {
      const now = Date.now();
      if (now - lastPingTime > 30000) {
        // 30秒没有收到心跳响应
        console.log(`用户 ${userId} 心跳超时，关闭连接`);
        ws.terminate();
        return;
      }

      if (ws.readyState === WebSocket.OPEN) {
        ws.send(JSON.stringify({ type: "ping" }));
      }
    }, 15000); // 每15秒发送一次心跳

    // 处理客户端消息
    ws.on("message", (message) => {
      try {
        const data = JSON.parse(message);

        switch (data.type) {
          case "message":
            // 构造新消息对象
            const newMessage = {
              type: "message",
              fromUserId: userId,
              fromUserType: userType,
              message: data.message,
              timestamp: new Date().toLocaleTimeString(),
            };

            // 保存到历史记录
            messageHistory.push(newMessage);

            // 根据用户类型发送消息
            if (userType === "customer") {
              // 如果是客户发送的消息，只发送给客服
              users.forEach((client, id) => {
                if (
                  client.userType === "service" &&
                  client.readyState === WebSocket.OPEN
                ) {
                  client.send(JSON.stringify(newMessage));
                }
              });
            } else {
              // 如果是客服发送的消息，只发送给客户
              users.forEach((client, id) => {
                if (
                  client.userType === "customer" &&
                  client.readyState === WebSocket.OPEN
                ) {
                  client.send(JSON.stringify(newMessage));
                }
              });
            }
            break;

          case "clearHistory":
            // 清空历史记录
            messageHistory.length = 0;
            console.log(`${userId} 清除了聊天历史记录`);
            
            // 通知所有连接的用户历史记录已被清除
            const clearMessage = {
              type: "historyCleaned",
              timestamp: new Date().toLocaleTimeString(),
            };
            
            users.forEach((client, id) => {
              if (client.readyState === WebSocket.OPEN) {
                client.send(JSON.stringify(clearMessage));
              }
            });
            break;

          case "setUserType":
            userType = data.userType;
            ws.userType = userType;
            console.log(`${userId} 设置为 ${userType}`);
            break;

          case "ping":
            // 收到客户端的心跳包，回复pong
            if (ws.readyState === WebSocket.OPEN) {
              ws.send(JSON.stringify({ type: "pong" }));
            }
            break;

          case "pong":
            lastPingTime = Date.now();
            ws.isAlive = true;
            break;
        }
      } catch (error) {
        console.error(`处理 ${userId} 的消息时出错:`, error);
      }
    });

    // 处理连接错误
    ws.on("error", (error) => {
      console.error(`${userId} 连接错误:`, error);
      clearInterval(heartbeatInterval);
      users.delete(userId);
    });

    // 处理连接关闭
    ws.on("close", () => {
      console.log(`${userId} 已断开连接`);
      clearInterval(heartbeatInterval);
      users.delete(userId);
    });
  } catch (error) {
    console.error("处理新连接时出错:", error);
    if (ws.readyState === WebSocket.OPEN) {
      ws.close();
    }
  }
});

console.log("WebSocket 服务已启动，运行在 ws://0.0.0.0:8088");
